package com.wr.recruit.service.apis;

import com.wr.recruit.service.service.AttachmentService;
import com.wr.recruit.service.utils.APIResponseSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;

@RestController
public class AttachmentApis {

    private AttachmentService attachmentService;

    @Autowired
    public AttachmentApis(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }

    @PostMapping(value = "/uploadFiles", produces = "application/json")
    @Transactional
    public APIResponseSet<String> handleAgreementFileUpload(@RequestParam("file") MultipartFile file,
                                                            @RequestParam("type") String type,
                                                            @RequestParam("code") String code){
        try {
            attachmentService.store(type, code, file);
        } catch (Exception e) {
            return new APIResponseSet<>(false,"文件上传失败");
        }
        return new APIResponseSet<>(true,"文件上传成功");
    }

    @GetMapping("/files/{attachmentCode}")
    @Transactional
    public String serveFile(@PathVariable("attachmentCode") String attachmentCode, HttpServletResponse response) throws Exception {
        Resource file = attachmentService.loadAsResource(attachmentCode);

        if (!file.exists())
            throw new Exception();

        response.reset();
        response.addHeader("Content-Disposition", "attachment;fileName=" + file.getFilename());
        response.setContentType("application/octet-stream");
        response.setContentLengthLong(file.contentLength());

        byte[] bytes = new byte[4096];
        byte[] result = (byte[]) Array.newInstance(byte.class, new Long(file.contentLength()).intValue());
        int count = 0;
        int counter = 0;

        try (OutputStream os = response.getOutputStream(); InputStream inputStream = file.getInputStream();) {
            while ((count = inputStream.read(bytes)) != -1) {
                System.arraycopy(bytes, 0, result, 4096 * counter, count);
                counter++;
            }
            os.write(result);
            os.flush();
        } catch (Exception e){
            throw new Exception();
        }
        return null;
    }

    @PostMapping(value = "/file/delete", produces = "application/json")
    @Transactional
    public APIResponseSet<String> deleteFile(@RequestParam("attachmentCode") String attachmentCode,
                                             @RequestParam("type") String type,
                                             @RequestParam("code") String code){
        try {
            attachmentService.deleteFile(type, code, attachmentCode);
        } catch (Exception e) {
            return new APIResponseSet<>(false,"文件删除失败");
        }
        return new APIResponseSet<>(true,"文件删除成功");
    }
}
